package org.example.com.editor.command.editorCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.command.Undoable;
import org.example.com.editor.command.commandHistory.CommandHistoryItem;
import org.example.com.editor.editor.Editor;
import org.example.com.editor.editor.TextEditor;
import org.example.com.editor.logger.LogManager;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AppendCommand implements Command, Undoable {
    String appendedText;
    private final LogManager logManager;

    public AppendCommand(LogManager logManager) {
        this.logManager = logManager;
    }

    @Override
    public void execute(Workspace workspace, ConsoleUI ui) {
        Map<String,Object> params = new HashMap<>();
        TextEditor editor = (TextEditor) workspace.getActiveEditor();

        if (editor == null) {
            ui.printError("没有活动文件，请先打开或新建文件");
            return;
        }

        String[] args = ui.getCommandArgs();
        if (args.length != 2) {
            ui.printError("用法：append <文本内容>");
            return;
        }
        String rawText = args[1];
        if (rawText.length() < 2 || !rawText.startsWith("\"") || !rawText.endsWith("\"")) {
            ui.printError("文本内容必须用双引号包裹");
            return;
        }

        appendedText = rawText.substring(1, args[1].length() - 1);

        params.put("text",appendedText);
        append(ui, editor, params);
        try {
            logManager.onCommandExecuted(workspace.getActiveFile(), args);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void undo(Editor editor, ConsoleUI ui,Map<String, Object> params) {
        String appendedText =(String) params.get("text");

        ((TextEditor)editor).undoAppend(appendedText);
    }

    @Override
    public void redo(Workspace workspace, ConsoleUI ui, Map<String, Object> params) {
        TextEditor editor = (TextEditor) workspace.getActiveEditor();
        appendedText =(String) params.get("text");
        append(ui, editor, params);
    }

    @Override
    public String getName() {
        return "append";
    }

    private void append(ConsoleUI ui, TextEditor editor, Map<String, Object> params) {
        try{
            editor.append(appendedText);
            editor.recordCommand(new CommandHistoryItem(this, params));
        }catch (IllegalArgumentException e){
            ui.printError(e.getMessage());
        }
    }

}